local skynet = require "skynet"
local filelog = require "filelog"
local msgproxy = require "msgproxy"
local configdao = require "configdao"
local base = require "base"
local tabletool = require "tabletool"
local timetool = require "timetool"
local helperbase = require "helperbase"
local logicmng = require "logicmng"
local playerdatadao = require "playerdatadao"
require "enum"

local TablesvrHelper = helperbase:new({
    writelog_tables = nil,
    })

function TablesvrHelper:sendmsg_to_alltableplayer(msgname, msg, ...)
    local table_data = self.server.table_data
    --通知座位上的玩家
    for _, seat in ipairs(table_data.seats) do
        if seat.state ~= ENNSeatState.SEAT_STATE_NO_PLAYER and seat.gatesvr_id ~= "" then
            filelog.sys_protomsg(msgname..":"..seat.rid, "____"..skynet.self().."_game_notice_____", msg)
            msgproxy.sendrpc_noticemsgto_gatesvrd(seat.gatesvr_id,seat.agent_address, msgname, msg, ...)
        end
    end
    --通知旁观玩家
    for rid, wait in pairs(table_data.waits) do
        filelog.sys_protomsg(msgname..":"..rid, "____"..skynet.self().."_game_notice_____", msg)
        if wait.gatesvr_id ~= "" then
            msgproxy.sendrpc_noticemsgto_gatesvrd(wait.gatesvr_id, wait.agent_address, msgname, msg, ...)
        end
    end
end

function TablesvrHelper:sendmsg_to_tableplayer(seat, msgname, ...)
    if seat.state ~= ENNSeatState.SEAT_STATE_NO_PLAYER and seat.gatesvr_id ~= "" then
        filelog.sys_protomsg(msgname..":"..seat.rid, "____"..skynet.self().."_game_notice_____", ...)
        msgproxy.sendrpc_noticemsgto_gatesvrd(seat.gatesvr_id,seat.agent_address, msgname, ...)
    end
end

function TablesvrHelper:sendmsg_to_allwaitplayer(msgname, msg, ...)
    local table_data = self.server.table_data
    for rid, wait in pairs(table_data.waits) do
        filelog.sys_protomsg(msgname..":"..rid, "____"..skynet.self().."_game_notice_____", msg)
        if wait.gatesvr_id ~= "" then
            msgproxy.sendrpc_noticemsgto_gatesvrd(wait.gatesvr_id, wait.agent_address, msgname, msg, ...)
        end
    end
end
function TablesvrHelper:sendmsg_to_waitplayer(wait, msgname, ...)
    if wait.gatesvr_id ~= "" then
        filelog.sys_protomsg(msgname..":"..wait.rid, "____"..skynet.self().."_game_notice_____", ...)
        msgproxy.sendrpc_noticemsgto_gatesvrd(wait.gatesvr_id, wait.agent_address, msgname, ...)
    end
end

--判断是否停止游戏
function TablesvrHelper:is_stop_game()
    local table_data = self.server.table_data
    return (table_data.state == ENNTableState.TABLE_STATE_UNKNOW)
end

--[[
message SeatInfo {
    optional int32 rid = 1;
    optional int32 index = 2;
    optional int32 state = 3;
    optional int32 is_tuoguan = 4; //1表示是 0表示否
    optional int32 gameid = 5;     //游戏id
    optional int32 cardsnum = 7;   //记录玩家手上剩余牌张数     

    optional PhzSeatInfo phzseatinfo = 6;

    optional NNSeatInfo nnseatinfo = 8;
}

message TablePlayerInfo {
    optional int32 rid = 1;
    optional string rolename = 2;
    optional string logo = 3;
    optional int32  sex = 4;    
    optional int32 gameid = 5;
    optional int32 coin = 6;
    optional int32 gemstone = 7;
    optional string ip = 8;
}

message ActionPlayerItem {
    optional int32 rid = 1;
    optional int32 roomsvr_seat_index = 2;    //当前操作玩家的座位号
    optional int32 action_to_time = 3;       //当前操作玩家的到期时间
    repeated int32 action_types = 4;         //玩家可以执行的操作类型
}

message GameInfo {
    optional int32 id = 1;    //table id
    optional int32 state = 2; //table state
    optional string name = 3; //桌子名字
    optional int32 room_type = 4; //房间类型
    optional int32 game_type = 5; //游戏类型
    optional int32 max_player_num = 6;   //房间支持的最大人数
    optional int32 cur_player_num = 7;   //状态服务器
    optional int32 retain_to_time = 8;   //桌子保留到的时间(linux时间擢)
    optional int32 retain_to_num = 9;    //游戏保留局数
    optional int32 curr_to_num = 10;     //游戏当前已经进行了的局数
    optional int32 create_user_rid = 11; //创建者rid
    optional string create_user_rolename = 12; //创建者姓名
    optional int32 create_time = 13;      //桌子的创建时间
    optional string create_table_id = 14; //创建桌子的索引id   
    optional string roomsvr_id = 15;      //房间服务器id
    optional int32 roomsvr_table_address = 16; //桌子table的地址
    optional string create_user_logo = 17;
    repeated ActionPlayerItem action_player_list = 18; 
    //下面两个结构按数组下标一一对应
    repeated SeatInfo seats = 19; //座位
    repeated TablePlayerInfo tableplayerinfos = 20;


    optional PhzGameinfo phzgameinfo = 21;

    optional NNGameinfo nngameinfo = 22;
}
]]

function TablesvrHelper:copy_table_gameinfo(gameinfo)
    local table_data = self.server.table_data
    gameinfo.id = table_data.id
    gameinfo.state = table_data.state
    gameinfo.name = table_data.conf.name
    gameinfo.room_type = table_data.conf.room_type
    gameinfo.max_player_num = table_data.conf.max_player_num
    gameinfo.cur_player_num = table_data.conf.cur_player_num
    gameinfo.retain_to_time = table_data.retain_to_time
    gameinfo.retain_to_num  = table_data.retain_to_num
    gameinfo.curr_to_num = table_data.curr_to_num
    gameinfo.create_user_rid = table_data.conf.create_user_rid
    gameinfo.create_user_rolename = table_data.conf.create_user_rolename
    gameinfo.create_time = table_data.conf.create_time
    gameinfo.create_table_id = table_data.conf.create_table_id
    gameinfo.create_user_logo = table_data.conf.create_user_logo

    gameinfo.roomsvr_id = table_data.svr_id
    gameinfo.roomsvr_table_address = skynet.self()


    gameinfo.nngameinfo = {
        gamecfg = {
            retain_to_num = table_data.conf.retain_to_num,
            pattern = table_data.conf.pattern,
            zuozhuang = table_data.conf.zuozhuang,
        },
    }
    
    gameinfo.nngameinfo.banker_seat_index = table_data.banker_seat_index

    
    gameinfo.action_player_list = {}
    if table_data.action_player_list ~= nil then
        local item = {}
        for _, value in pairs(table_data.action_player_list) do
            item.rid = value.rid
            item.roomsvr_seat_index = value.roomsvr_seat_index
            item.action_to_time = value.action_to_time
            item.action_types = value.action_types
            table.insert(gameinfo.action_player_list, item)
        end
    end

    gameinfo.seats = {}
    gameinfo.tableplayerinfos = {}
    local seatinfo, tableplayerinfo
    for index, seat in pairs(table_data.seats) do
        seatinfo = {}
        tableplayerinfo = {}
        self:copy_seatinfo(seatinfo, seat)
        table.insert(gameinfo.seats, seatinfo)
        self:copy_tableplayerinfo(tableplayerinfo, seat)
        table.insert(gameinfo.tableplayerinfos, tableplayerinfo)
    end

end

function TablesvrHelper:copy_seatinfo(seatinfo, seat)
    local table_data = self.server.table_data
    seatinfo.rid = seat.rid
    seatinfo.index = seat.index
    seatinfo.state = seat.state
    seatinfo.is_tuoguan = seat.is_tuoguan
    seatinfo.gameid = table_data.conf.gameid
    seatinfo.cardsnum = 0
    seatinfo.nnseatinfo = {}

    seatinfo.nnseatinfo.curr_score = seat.curr_score
    seatinfo.nnseatinfo.total_score = seat.total_score
    seatinfo.nnseatinfo.call_score = seat.call_score
    seatinfo.nnseatinfo.bankertag = seat.bankertag
    seatinfo.nnseatinfo.win_num = seat.win_num
    seatinfo.nnseatinfo.continue_banker_count = seat.continue_banker_count

    if table_data.state == ENNTableState.TABLE_STATE_WAIT_PINGNIU 
        and seat.final_cards ~= nil then
       seatinfo.nnseatinfo.is_pingniu = 1 
    else
       seatinfo.nnseatinfo.is_pingniu = 0 
    end 
        
end

function TablesvrHelper:copy_tableplayerinfo(tableplayerinfo, seat)
    local table_data = self.server.table_data
    tableplayerinfo.rid = seat.rid
    tableplayerinfo.rolename = seat.playerinfo.rolename
    tableplayerinfo.logo = seat.playerinfo.logo
    tableplayerinfo.sex = seat.playerinfo.sex
    tableplayerinfo.gameid = table_data.conf.gameid
    tableplayerinfo.coin = seat.coin
    tableplayerinfo.gemstone = seat.gemstone
    tableplayerinfo.roomcard = seat.roomcard
    tableplayerinfo.ip = seat.playerinfo.ip

end


--用于输出指定table_id桌子的信息，方便定位问题
function TablesvrHelper:write_tableinfo_log(...)
    --[[if self.writelog_tables == nil then
        self.writelog_tables = configdao.get_common_conf("tables")
    end

    if self.writelog_tables == nil then
        return
    end]]
    --if self.writelog_tables[self.server.table_data.id] ~= nil then
        filelog.sys_obj("table", self.server.table_data.id, ...)           
    --end 
end

--记录调试日志
function TablesvrHelper:write_debug_log(classname, objname, ...)
    if base.isdebug() then
        filelog.sys_obj(classname, objname, ...)
    end
end

function TablesvrHelper:report_table_state()
    local table_data = self.server.table_data
    --上报table
    local table_state = {
        id = table_data.id,
        state = table_data.state,
        name = table_data.conf.name,
        gameid = table_data.conf.gameid,
        room_type = table_data.conf.room_type,
        max_player_num = table_data.conf.max_player_num,
        cur_player_num = table_data.sitdown_player_num,
        retain_to_num =  table_data.retain_to_num,
        curr_to_num =    table_data.curr_to_num,
        retain_to_time = table_data.retain_to_time,

        create_user_rid = table_data.conf.create_user_rid,
        create_user_rolename = table_data.conf.create_user_rolename,
        create_user_logo = table_data.conf.create_user_logo,
        create_time = table_data.conf.create_time,
        create_table_id = table_data.conf.create_table_id,
        action_timeout = table_data.conf.action_timeout,
        action_timeout_count = table_data.conf.action_timeout_count,           

        roomsvr_id = table_data.svr_id,
        roomsvr_table_address = skynet.self(),        

        nngamecfg = {
            retain_to_num = table_data.conf.retain_to_num,
            pattern = table_data.conf.pattern,
            zuozhuang = table_data.conf.zuozhuang,
        },
    }
    msgproxy.sendrpc_broadcastmsgto_tablesvrd("update", table_data.conf.gameid, table_data.svr_id, table_state)
end

function TablesvrHelper:get_game_logic()
    local table_data = self.server.table_data  
    if table_data.conf.room_type == ENNRoomType.NNROOM_TYPE_COMMON then
        return logicmng.get_logicbyname("roomgamelogic")
    elseif table_data.conf.room_type == ENNRoomType.NNROOM_TYPE_FRIEND_COMMON then
        return logicmng.get_logicbyname("roomfndgamelogic")
    elseif table_data.conf.room_type == ENNRoomType.NNROOM_TYPE_FRIEND_QIANGZHUANG then
        return logicmng.get_logicbyname("roomfndgamelogic3")
    elseif table_data.conf.room_type == ENNRoomType.NNROOM_TYPE_FRIEND_LUNLIUZHUANG then
        return logicmng.get_logicbyname("roomfndgamelogic4")
    elseif table_data.conf.room_type == ENNRoomType.NNROOM_TYPE_FRIEND_GUIDIZHUANG then
        return logicmng.get_logicbyname("roomfndgamelogic5")
    end
end

function TablesvrHelper:generate_table_key()
    local table_data = self.server.table_data 
    return (table_data.svr_id..table_data.conf.gameid..table_data.conf.id..timetool.get_10ms_time())     
end

function TablesvrHelper:save_player_record()
    local table_data = self.server.table_data
    if  table_data.gamerecords == nil then
        return
    end
    
    for _, record in pairs(table_data.gamerecords.playerrecordlist) do
        playerdatadao.save_player_tablerecords("insert", record.rid, table_data.gamerecords)
    end 
end

return  TablesvrHelper